<template>
  <el-card class="bigCard">
    <page-tool @showaddRoles="showaddRoles" />
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="title" label="角色名称" width="350" />
      <el-table-column prop="description" label="角色描述" width="500" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-row type="flex" justify="center">
            <el-button size="small" type="success" @click="asignPerm(scope.row.id)">分配权限</el-button>
            <el-button size="small" @click="updateRoles(scope.row.id)">编辑</el-button>
            <el-button size="small" type="danger" @click="delRoles(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分配权限弹窗 -->
    <asign-perm ref="asignPerm" :visible-dialog.sync="isShowDialog" :check-list="checkList" :cur-id="curId" />

    <!-- 新增角色弹窗 -->
    <add-roles ref="addRolesDialog" :add-roles-dialog.sync="isShow" @loadRolesList="loadRolesList" />
  </el-card>
</template>

<script>
import { getRolesList, getRolesById, delRoles } from '@/api/roles'
import asignPerm from '@/views/roles/components/asign-Perm'
import PageTool from './components/page-tool.vue'
import AddRoles from './components/add-roles.vue'

export default {
  components: {
    'asign-perm': asignPerm,
    PageTool,
    AddRoles
  },
  data() {
    return {
      tableData: [
        {
          title: '',
          description: ''
        }
      ],
      pageSizes: {
        _limit: 3,
        _start: 0
      },
      isShowDialog: false, // 控制分配弹窗显示
      isShow: false, // 控制新增角色弹窗显示
      curId: -1, // 当前的id
      checkList: []
    }
  },
  created() {
    this.loadRolesList()
  },
  methods: {
    // 获取角色列表
    async loadRolesList() {
      const res = await getRolesList()
      this.tableData = res.data
    },

    // 分配权限
    async asignPerm(id) {
      this.curId = id
      this.isShowDialog = true
      const res = await getRolesById(id)
      this.checkList = res.data.permissions
      // 数据回显
      this.$refs.asignPerm.isCheckList()
    },

    // 显示新增角色弹窗
    showaddRoles() {
      this.isShow = true
    },

    // 编辑角色
    async updateRoles(id) {
      this.curId = id
      this.isShow = true // 显示弹窗
      const res = await getRolesById(id)
      console.log(res.data)
      this.$refs.addRolesDialog.rolesForm = res.data // 数据回显
    },

    // 删除角色
    delRoles(id) {
      // 确认框
      this.$confirm('是否删除角色?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await delRoles(id)
          this.loadRolesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-button--default {
  background-color: #388fd5;
}
</style>
